package com.jason.quectel0805.activities;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;

import com.jason.quectel0805.R;

import java.util.concurrent.ScheduledExecutorService;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {
    private int second = 5;
    private TextView tvShow;

    private ScheduledExecutorService executorService;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    tvShow.setText("跳过" + msg.obj + "s");
                    if (((int) msg.obj) <= 0) {
                        WebViewActivity.gotoWebView(SplashActivity.this, "https://www.baidu.com/");
                        //startActivity(new Intent(SplashActivity.this, MainActivity.class));
                        finish();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdownNow();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        tvShow = findViewById(R.id.tv_splash_show);

        //executorService = Executors.newSingleThreadScheduledExecutor();
        //executorService.scheduleAtFixedRate(new Runnable() {
        //    @Override
        //    public void run() {
        //        second--;
        //        Message obtain = Message.obtain();
        //        obtain.what = 1;
        //        obtain.obj = second;
        //        handler.sendMessage(obtain);
        //    }
        //}, 1000, 1000, TimeUnit.MILLISECONDS);

        //    利用Thread手动完成一个周期任务的实现
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (second > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    second--;
                    Message obtain = Message.obtain();
                    obtain.what = 1;
                    obtain.obj = second;
                    handler.sendMessage(obtain);
                }
            }
        }).start();
    }
}